import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sensor_backend/assets/color.dart';
import 'package:flutter_sensor_backend/assets/showPop.dart';
import 'package:flutter_sensor_backend/component/niw.dart';
import 'package:flutter_sensor_backend/middleware/mid_interface.dart';
import 'package:sensors_plus/sensors_plus.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import 'package:toast/toast.dart';

class SalesData {
  SalesData(this.index, this.data);
  final int index;
  final double data;
}

class PushData extends StatefulWidget {
  const PushData({super.key});

  @override
  State<PushData> createState() => _PushDataState();
}

class _PushDataState extends State<PushData> {
  refresh() {
    int range = 50;
    if (chartDataX.length > range) {
      chartDataX = chartDataX.sublist(chartDataX.length - range);
    }
    if (chartDataY.length > range) {
      chartDataY = chartDataY.sublist(chartDataY.length - range);
    }
    if (chartDataZ.length > range) {
      chartDataZ = chartDataZ.sublist(chartDataZ.length - range);
    }
  }

  int getTimeStamp() {
    return DateTime.now().millisecondsSinceEpoch;
  }

  getSensor() {
    int cnt = 1;
    int cntNum = 1;
    int pushSpace = Platform.isAndroid ? 1 : 5; // -> 5
    int stateSpace = Platform.isAndroid ? 1 : 10; // -> 10
    int stamp = getTimeStamp();
    accelerometerEvents.listen((AccelerometerEvent event) {
      if (startCollect) {
        dx.add(event.x);
        dy.add(event.y);
        dz.add(event.z);
      }
      if (cntNum % pushSpace == 0) {
        chartDataX.add(SalesData(cnt, event.x));
        chartDataY.add(SalesData(cnt, event.y));
        chartDataZ.add(SalesData(cnt, event.z));
        cnt++;
        refresh();
      }
      if (cntNum % stateSpace == 0) {
        try {
          setState(() {});
        } catch (e) {}
      }
      cntNum++;
    });
  }

  DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
  String infoTxt = "";

  getDeviceInfo() async {
    if (Platform.isIOS) {
      IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
      infoTxt = iosInfo.utsname.machine!;
    }
    if (Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      infoTxt = androidInfo.model;
    }
  }

  ping() async {
    Response res = await Dio().get("http://baidu.com");
    // print("${res.data}");
  }

  @override
  void initState() {
    getSensor();
    getDeviceInfo();
    ping();
    super.initState();
  }

  List<SalesData> chartDataX = [];

  List<SalesData> chartDataY = [];

  List<SalesData> chartDataZ = [];

  bool isFall = false;
  bool startCollect = false;
  bool sampling = false;
  List<double> dx = [];
  List<double> dy = [];
  List<double> dz = [];

  sample() async {
    showPopWithHeight(
      context,
      [
        Container(height: 40),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              "请注意",
              style: TextStyle(
                color: os_black,
                fontSize: 23,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
        Container(height: 25),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 25),
          child: Text.rich(
            TextSpan(
              text:
                  "采集时间持续5秒种，采集成功之后可以在平台中查看/修改/删除此数据，采集期间请尽可能还原真实场景；如果需要连续采集，请使用",
              children: [
                WidgetSpan(
                  child: GestureDetector(
                    onTap: () {
                      Navigator.of(context).pop();
                      Navigator.of(context).pushNamed("/use_api");
                    },
                    child: Text(
                      "Api接口>",
                      style: TextStyle(
                        color: os_black,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ],
            ),
            style: TextStyle(
              color: os_black,
              fontSize: 16,
              fontWeight: FontWeight.normal,
              height: 2,
            ),
            textAlign: TextAlign.center,
          ),
        ),
        Container(height: 40),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            myInkWell(
              tap: () {
                Navigator.of(context).pop();
              },
              color: os_color_opa,
              widget: Container(
                width: (MediaQuery.of(context).size.width - 40) / 2,
                height: 50,
                child: Center(
                  child: Text(
                    "取消",
                    style: TextStyle(
                      color: os_color,
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
              radius: 100,
            ),
            Container(width: 10),
            myInkWell(
              color: os_color,
              tap: () {
                Navigator.of(context).pop();
                confirmSend();
              },
              widget: Container(
                width: (MediaQuery.of(context).size.width - 40) / 2,
                height: 50,
                child: Center(
                  child: Text(
                    "确定",
                    style: TextStyle(
                      color: os_white,
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
              radius: 100,
            ),
          ],
        ),
      ],
      400,
    );
  }

  confirmSend() async {
    Toast.show(
      "请稍后…",
      duration: Toast.lengthLong,
      gravity: Toast.center,
    );
    if (sampling) return;
    setState(() {
      sampling = true;
    });
    startCollect = true;
    await Future.delayed(const Duration(seconds: 5));
    startCollect = false;
    Map<String, dynamic> sendData = {};

    if (dx.length < 20) {
      Toast.show(
        "手机采样频率不够，请更换设备",
        textStyle: const TextStyle(
          color: Colors.red,
        ),
        duration: Toast.lengthShort,
        gravity: Toast.bottom,
      );
      return;
    } else if (dx.length > 20 && dx.length < 100) {
      sendData = {
        'seqDataX': "[${dx.join(',')}]",
        'seqDataY': "[${dy.join(',')}]",
        'seqDataZ': "[${dz.join(',')}]",
      };
    } else {
      int gap = dx.length ~/ 100;
      int p = 0;
      List<double> dxTmp = [];
      List<double> dyTmp = [];
      List<double> dzTmp = [];
      while (p < dx.length) {
        dxTmp.add(dx[p]);
        dyTmp.add(dy[p]);
        dzTmp.add(dz[p]);
        p += gap;
      }
      sendData = {
        'seqDataX': "[${dxTmp.join(',')}]",
        'seqDataY': "[${dyTmp.join(',')}]",
        'seqDataZ': "[${dzTmp.join(',')}]",
      };
    }
    sendData.addAll({
      'fallDown': isFall ? 'true' : 'false',
      'timestamp': getTimeStamp().toString(),
      'deviceInfo': infoTxt,
    });

    var response = await Api().AddCollection(sendData);

    print(response.toString());

    if (response["msg"] == "ok") {
      Toast.show(
        "采样成功！",
        duration: Toast.lengthShort,
        gravity: Toast.center,
      );
    }
    dx = [];
    dy = [];
    dz = [];
    setState(() {
      sampling = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
      padding: EdgeInsets.only(top: 7.5),
      decoration: BoxDecoration(
        color: os_white,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Container(
            padding: EdgeInsets.symmetric(vertical: 10),
            child: Opacity(
              opacity: sampling ? 0.3 : 1,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  myInkWell(
                    tap: () {
                      isFall = false;
                      sample();
                    },
                    color: Color(0xffFFC754),
                    widget: Container(
                      padding:
                          EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                      child: Text(
                        "采集为非跌倒数据",
                        style: TextStyle(
                          color: Color(0xff584216),
                          fontSize: 14,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    radius: 100,
                  ),
                  Container(width: 10),
                  myInkWell(
                    tap: () {
                      isFall = true;
                      sample();
                    },
                    color: Color(0xff0045F9),
                    widget: Container(
                      padding:
                          EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                      child: Text(
                        "采集为跌倒数据",
                        style: TextStyle(
                          color: os_white,
                          fontSize: 14,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    radius: 100,
                  ),
                ],
              ),
            ),
          ),
          MyChart(
            chartDataX: chartDataX,
            chartDataY: chartDataY,
            chartDataZ: chartDataZ,
          ),
        ],
      ),
    );
  }
}

class MyChart extends StatefulWidget {
  final List<SalesData> chartDataX;
  final List<SalesData> chartDataY;
  final List<SalesData> chartDataZ;
  MyChart({
    super.key,
    required this.chartDataX,
    required this.chartDataY,
    required this.chartDataZ,
  });

  @override
  State<MyChart> createState() => _MyChartState();
}

class _MyChartState extends State<MyChart> {
  @override
  Widget build(BuildContext context) {
    return SfCartesianChart(
      enableAxisAnimation: true,
      tooltipBehavior: TooltipBehavior(
        enable: true,
        shared: true,
      ),
      legend: Legend(
        isVisible: true,
        position: LegendPosition.bottom,
      ),
      series: <ChartSeries>[
        LineSeries<SalesData, int>(
          name: "X轴",
          dataSource: widget.chartDataX,
          xValueMapper: (SalesData sensorData, _) => sensorData.index,
          yValueMapper: (SalesData sensorData, _) => sensorData.data,
        ),
        LineSeries<SalesData, int>(
          name: "Y轴",
          dataSource: widget.chartDataY,
          xValueMapper: (SalesData sensorData, _) => sensorData.index,
          yValueMapper: (SalesData sensorData, _) => sensorData.data,
        ),
        LineSeries<SalesData, int>(
          name: "Z轴",
          dataSource: widget.chartDataZ,
          xValueMapper: (SalesData sensorData, _) => sensorData.index,
          yValueMapper: (SalesData sensorData, _) => sensorData.data,
        ),
      ],
    );
  }
}
